/*
 * Created on 2005-3-4
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package core.upintf;

import io.ReconnableAsyncSocket;
import io.ReconnableAsyncSocketException;
import io.beattest.ServerRepliableSocketBeatTest;

import java.net.UnknownHostException;
import java.util.Timer;

import org.apache.log4j.Logger;

import protocol.FrameGenerator;
import protocol.pv.PVCommand;

/**
 * @author pdv
 *
 */
public class DMClient implements UpInterface {
	private static final Logger logger = Logger.getLogger(DMClient.class);
	
	private ReconnableAsyncSocket client;
	
	public void close() {
		this.client.close();
	}
	
//	private ReconnableAsyncSocket getDMSocket() {
//		return this.client;
//	}
	
	public boolean write(PVCommand pvCommand) {
//		if (!AppProperties.CONFIG.DM.send)
//			return true;
		return this.client.write(FrameGenerator.genFrame(pvCommand.output()));
	}
	
	private ServerRepliableSocketBeatTest clientBeatTask;
	public ServerRepliableSocketBeatTest getClientBeatTask() {
		return this.clientBeatTask;
	}
	
	private void initClient(String host,int port,int retryTime) {
		try {
			client = new ReconnableAsyncSocket(host,port);
			client.setEventListener(new DMClientEventListener(this));
			client.setRetryTime(retryTime);
		} catch (UnknownHostException e) {
			logger.fatal("DM host:"+ host+" unknown");
			System.exit(1);		
		} catch (ReconnableAsyncSocketException e) {
			logger.fatal("Processor.initDMClient", e);
			System.exit(1);
		}	
	}
	
	private void initClientBeatTask() {
		this.clientBeatTask = new ServerRepliableSocketBeatTest( client, 
				FrameGenerator.genFrame(new PVCommand(PVCommand.SOCKET_BEAT).output() ));
		
	}
	
	public void run() {
		this.runClient();
		this.runClientBeatTask();
	}
	
	/**
	 * 
	 */
	private void runClientBeatTask() {
		int timeout =30000;
		new Timer(true).schedule(clientBeatTask, timeout, timeout);
		logger.info("dm socket beat task is set");
	}

	/**
	 * 
	 */
	private void runClient() {
		client.open();
	}

	public DMClient(String host,int port,int retryTime) {
		this.initClient(host,port,retryTime);
		this.initClientBeatTask();
	}

	public boolean isConnected() {
		return this.client.isConnected();
	}

	public void closeTemporarily() {
		this.client.closeTemporarily();
	}
}
